import {HttpClient, HttpHeaders, HttpResponse} from '@angular/common/http';
import {StorageUtil} from './storage.util';
import {NzMessageService} from 'ng-zorro-antd';
import {Injectable} from '@angular/core';
import {LoadingServer} from '../common/loading/loading.server';

/**
 * @Description: post文件下载，后台返回文件类型
 * @author YangHui
 * @data: 2020年12月18日
 */
@Injectable()
export class PostDown {
  constructor(
    protected httpclient: HttpClient,
    protected message: NzMessageService,
    protected loading: LoadingServer) {
  }

  /**
   * post导出文件函数
   * @param urls:导出地址
   * @param param1 导出参数
   * @param workTypeName 工种名称
   */
  postDownload(urls, param1, workTypeName?: string): any {
    const that = this;
    that.loading.load();
    that.httpclient.post(urls, param1, {
      headers: new HttpHeaders({Authorization: StorageUtil.getLocalStorage('token')}),
      observe: 'response',
      responseType: 'blob'
    }).subscribe((res: HttpResponse<Blob>) => {
      if (res) {
        that.loading.hide();
        const data = res.body;
        const r = new FileReader();
        r.readAsText(data);
        r.onload = function(e) {
          try {
            if (typeof this.result === 'string') {
              const resData = JSON.parse(this.result);
              that.message.warning(resData.message);
            }
          } catch (err) {
            const blob = res.body;
            const url = URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            const contentDisposition = res.headers.get('Content-Disposition');
            if (contentDisposition) {
              const fileName = contentDisposition.split(';')[1].split('=')[1];
              const name = workTypeName ?
                decodeURI(fileName).split('_')[0] + '_' + workTypeName + '_' + decodeURI(fileName).split('_')[1] :
                decodeURI(fileName);
              a.download = decodeURI(name);
              a.click();
              URL.revokeObjectURL(url);
              that.message.success('操作成功');
            } else {
              that.message.warning('操作失败!');
            }
          }
        };
      }
    });
  }

  /**
   * post导出文件函数
   * @param urls:导出地址
   * @param param1 导出参数
   * @param fileName 文件名
   */
  postDownloadZip(urls, param1, fileName): any {
    const that = this;
    that.loading.load();
    that.httpclient.post(urls, param1, {
      headers: new HttpHeaders({Authorization: StorageUtil.getLocalStorage('token')}),
      observe: 'response',
      responseType: 'blob'
    }).subscribe((res: HttpResponse<Blob>) => {
      const data = res.body;
      const r = new FileReader();
      r.readAsText(data);
      r.onload = function() {
        try {
          if (typeof this.result === 'string') {
            const jsonData = JSON.parse(this.result);
            that.message.warning(jsonData.message);
          }
        } catch (error) {
          // @ts-ignore
          const blob = new Blob([res.body], {type: 'application/zip'});
          const url = URL.createObjectURL(blob);
          const a = document.createElement('a');
          a.href = url;
          a.download = fileName;
          a.click();
          URL.revokeObjectURL(url);
        }
      };
    });
  }
}
